<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="户号" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入户号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表号" prop="meterNo">
        <el-input
          v-model="queryParams.meterNo"
          placeholder="请输入表号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="充值时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
<!--      <el-form-item label="充值时间" prop="chargeDate">
        <el-date-picker clearable
          v-model="queryParams.chargeDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="充值时间">
        </el-date-picker>
      </el-form-item>-->
<!--      <el-form-item label="充值方式" prop="topUpType">
        <el-select v-model="queryParams.topUpType" placeholder="请选择充值方式" clearable>
          <el-option
            v-for="dict in dict.type.top_up_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>-->
      <el-form-item label="充值状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择充值状态" clearable>
          <el-option
            v-for="dict in dict.type.charge_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="充值类型" prop="payType">
        <el-select v-model="queryParams.payType" placeholder="请选择充值类型" clearable>
          <el-option
            v-for="dict in dict.type.pay_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="false">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['revenue:rechargeRecord:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['revenue:rechargeRecord:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['revenue:rechargeRecord:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['revenue:rechargeRecord:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rechargeRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" v-if="false"/>
      <el-table-column label="充值订单号" align="center" prop="ordersn" v-if="false"/>
      <el-table-column label="户号" align="center" prop="userId" />
      <el-table-column label="表号" align="center" prop="meterNo" />
      <el-table-column label="缴费金额" align="center" prop="money" />
      <el-table-column label="缴费时间" align="center" prop="chargeDate" width="180">
<!--        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.chargeDate, '{y}-{m}-{d}') }}</span>
        </template>-->
      </el-table-column>
<!--      <el-table-column label="充值结果" align="center" prop="chargeResult">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.charge_result" :value="scope.row.chargeResult"/>
        </template>
      </el-table-column>-->
      <el-table-column label="到表时间" align="center" prop="topUpDate" width="180">
<!--        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.topUpDate, '{y}-{m}-{d}') }}</span>
        </template>-->
      </el-table-column>
<!--      <el-table-column label="充值方式" align="center" prop="topUpType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.top_up_type" :value="scope.row.topUpType"/>
        </template>
      </el-table-column>-->
      <el-table-column label="缴费状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.charge_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="是否打印" align="center" prop="isPrint" v-if="false">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.custom_yes_no" :value="scope.row.isPrint"/>
        </template>
      </el-table-column>
      <el-table-column label="缴费类型" align="center" prop="payType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pay_type" :value="scope.row.payType"/>
        </template>
      </el-table-column>
      <el-table-column label="操作员" align="center" prop="oper" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handlePrint(scope.row)"
          >补打发票</el-button>
<!--          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['revenue:rechargeRecord:remove']"
          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 发票弹窗 -->
    <el-dialog title="发票预览" :visible.sync="printVisible" width="60%">
      <div id="printArea" class="invoice-container">
        <!-- 发票预览内容 -->
        <div class="invoice-header">
          <h1>{{ invoice.type }}</h1>
          <p>发票代码：{{ invoice.code }} | 发票号码：{{ invoice.number }} | 开票日期：{{ invoice.date }}</p>
        </div>
        <div class="invoice-body">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="invoice-section">
                <h3>购买方信息</h3>
                <p>名称：{{ invoice.buyer.name }}</p>
                <p>纳税人识别号：{{ invoice.buyer.taxId }}</p>
                <p>地址、电话：{{ invoice.buyer.address }}</p>
                <p>开户行及账号：{{ invoice.buyer.bank }}</p>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="invoice-section">
                <h3>销售方信息</h3>
                <p>名称：{{ invoice.seller.name }}</p>
                <p>纳税人识别号：{{ invoice.seller.taxId }}</p>
                <p>地址、电话：{{ invoice.seller.address }}</p>
                <p>开户行及账号：{{ invoice.seller.bank }}</p>
              </div>
            </el-col>
          </el-row>
          <!-- 使用标准表格替代Element UI表格，确保打印边框 -->
          <table class="invoice-table">
            <thead>
            <tr>
              <th>商品名称</th>
              <th width="80">数量</th>
              <th width="90">金额</th>
              <th width="80">单位</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item, index) in invoice.items" :key="index">
              <td>{{ item.name }}</td>
              <td>{{ item.quantity }}</td>
              <td>{{ item.amount.toFixed(2) }}</td>
              <td>{{ item.unit }}</td>
            </tr>
            </tbody>
          </table>
          <div class="invoice-total">
            <p>合计（大写）：{{ amountInWords }} | 小写：¥{{ totalAmount.toFixed(2) }}</p>
          </div>
          <div class="invoice-remark" v-if="false">
            <p>备注：{{ invoice.remark }}</p>
          </div>
        </div>
        <div class="invoice-footer">
          <p>开票人：{{ invoice.drawer }} | 收款人：{{ invoice.payee }} | 复核人：{{ invoice.reviewer }}</p>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-print="printObj" type="primary">打 印</el-button>
        <el-button @click="printVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 添加或修改充值记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="充值订单号" prop="ordersn">
          <el-input v-model="form.ordersn" placeholder="请输入充值订单号" />
        </el-form-item>
        <el-form-item label="户号" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入户号" />
        </el-form-item>
        <el-form-item label="表索引号" prop="meterId">
          <el-input v-model="form.meterId" placeholder="请输入表索引号" />
        </el-form-item>
        <el-form-item label="表号" prop="meterNo">
          <el-input v-model="form.meterNo" placeholder="请输入表号" />
        </el-form-item>
        <el-form-item label="充值序号" prop="ser">
          <el-input v-model="form.ser" placeholder="请输入充值序号" />
        </el-form-item>
        <el-form-item label="充值金额" prop="money">
          <el-input v-model="form.money" placeholder="请输入充值金额" />
        </el-form-item>
        <el-form-item label="充值操作时间" prop="chargeDate">
          <el-date-picker clearable
            v-model="form.chargeDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择充值操作时间">
          </el-date-picker>
        </el-form-item>
<!--        <el-form-item label="充值结果" prop="chargeResult">
          <el-input v-model="form.chargeResult" placeholder="请输入充值结果" />
        </el-form-item>-->
        <el-form-item label="充值到表成功时间" prop="topUpDate">
          <el-date-picker clearable
            v-model="form.topUpDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择充值到表成功时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="充值方式" prop="topUpType">
          <el-select v-model="form.topUpType" placeholder="请选择充值方式">
            <el-option
              v-for="dict in dict.type.top_up_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充值机构代码" prop="orgCode">
          <el-input v-model="form.orgCode" placeholder="请输入充值机构代码" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-input v-model="form.state" placeholder="请输入状态" />
        </el-form-item>
        <el-form-item label="是否打印" prop="isPrint">
          <el-select v-model="form.isPrint" placeholder="请选择是否打印">
            <el-option
              v-for="dict in dict.type.custom_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充值类型" prop="payType">
          <el-select v-model="form.payType" placeholder="请选择充值类型">
            <el-option
              v-for="dict in dict.type.pay_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作员" prop="oper">
          <el-input v-model="form.oper" placeholder="请输入操作员" />
        </el-form-item>
        <el-form-item label="返回请求ID" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入返回请求ID" />
        </el-form-item>
        <el-form-item label="结果描述">
          <editor v-model="form.resultContent" :min-height="192"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRechargeRecord} from "@/api/revenue/invoice";

export default {
  name: "Invoice",
  dicts: ['pay_type', 'top_up_type', 'custom_yes_no', 'charge_state'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 充值记录表格数据
      rechargeRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      printVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        meterNo: null,
        topUpDate: null,
        topUpType: null,
        state: null,
        payType: null,
      },
      // 默认发票数据，如果父组件传入则使用传入的数据
      invoice: {
        type: '增值税普通发票',
        code: '12345678',
        number: '87654321',
        date: '2025-09-18',
        buyer: {
          name: '北京某某科技有限公司',
          taxId: '91110105MA7GXXXXX',
          address: '北京市朝阳区某某路1号 010-12345678',
          bank: '中国工商银行某某支行 0200xxxxxx'
        },
        seller: {
          name: '上海某某实业有限公司',
          taxId: '91310110MA7GXXXXX',
          address: '上海市浦东新区某某路88号 021-98765432',
          bank: '中国建设银行某某支行 0300xxxxxx'
        },
        items: [
          { name: '用水缴费', unit: '元', quantity: 1, amount: 5000.00 }
        ],
        remark: '请在收到发票后30日内付款',
        drawer: '张三',
        reviewer: '李四',
        payee: '王五'
      },
      // 打印配置:cite[8]
      printObj: {
        id: 'printArea', // 要打印的区域ID
        popTitle: '发票打印', // 打印标题
        extraCss: '', // 附加的CSS样式
        extraHead: '<meta http-equiv="Content-Language" content="zh-cn"/>' // 额外的HEAD标签
      },
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    const userId = this.$route.params && this.$route.params.userId;
    this.queryParams.userId = userId;
    this.getList();
  },
  computed: {
    // 计算总金额
    totalAmount() {
      return this.invoice.items.reduce((sum, item) => {
        return sum + item.amount;
      }, 0);
    },
    // 金额大写转换（简单示例）
    amountInWords() {
      const number = this.invoice.items[0].amount || 0;
      if (number === 0) return '零元整';

      // 简单实现金额大写转换
      const cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
      const cnIntRadice = ['', '拾', '佰', '仟'];
      const cnIntUnits = ['', '万', '亿', '兆'];
      const cnDecUnits = ['角', '分', '毫', '厘'];
      const cnInteger = '整';

      let integerNum = Math.floor(number);
      let decimalNum = Math.round((number - integerNum) * 100);

      let chineseStr = '';

      // 整数部分
      if (integerNum > 0) {
        let integerStr = integerNum.toString();
        let zeroCount = 0;
        for (let i = 0; i < integerStr.length; i++) {
          let n = integerStr.substr(i, 1);
          let p = integerStr.length - i - 1;
          let q = p / 4;
          let m = p % 4;

          if (n == '0') {
            zeroCount++;
          } else {
            if (zeroCount > 0) {
              chineseStr += cnNums[0];
            }
            zeroCount = 0;
            chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
          }

          if (m == 0 && zeroCount < 4) {
            chineseStr += cnIntUnits[q];
          }
        }
        chineseStr += '元';
      }

      // 小数部分
      if (decimalNum > 0) {
        let decimalStr = decimalNum.toString().padStart(2, '0');
        for (let i = 0; i < decimalStr.length; i++) {
          let n = decimalStr.substr(i, 1);
          if (n !== '0') {
            chineseStr += cnNums[Number(n)] + cnDecUnits[i];
          }
        }
      } else {
        chineseStr += cnInteger;
      }

      return chineseStr;
    }
  },
  methods: {
    /** 查询充值记录列表 */
    getList() {
      this.loading = true;
      listRechargeRecord(this.addDateRange(this.queryParams,this.dateRange)).then(response => {
        this.rechargeRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        meterNo: null,
        chargeDate: null,
        chargeResult: null,
        topUpDate: null,
        topUpType: null,
        state: null,
        payType: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加充值记录";
    },
    handlePrint(row){
      this.printVisible = true;
      this.invoice.items = [{ name: '用水缴费', unit: '元', quantity: 1, amount: row.money }]
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRechargeRecord(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改充值记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRechargeRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRechargeRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除充值记录编号为"' + ids + '"的数据项？').then(function() {
        return delRechargeRecord(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('revenue/rechargeRecord/export', {
        ...this.queryParams
      }, `rechargeRecord_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.invoice-container {
  padding: 20px;
  background-color: #fff;
}
.invoice-header {
  text-align: center;
  margin-bottom: 20px;
  border-bottom: 2px solid #409EFF;
  padding-bottom: 10px;
}
/* 表格边框优化 */
.invoice-table {
  width: 100%;
  margin-top: 20px;
  border-collapse: collapse;
}
.invoice-table th,
.invoice-table td {
  border: 1px solid #000;
  padding: 8px 10px;
  text-align: center;
}
.invoice-table th {
  background-color: #f5f7fa;
}

.invoice-section {
  margin-bottom: 15px;
}
.invoice-total {
  text-align: right;
  margin-top: 20px;
  font-weight: bold;
}
.invoice-remark {
  margin-top: 15px;
}
.invoice-footer {
  margin-top: 30px;
  text-align: center;
  border-top: 1px dashed #ddd;
  padding-top: 10px;
}

/* 打印样式优化 */
@media print {
  body * {
    visibility: hidden;
  }
  #printArea, #printArea * {
    visibility: visible;
  }
  #printArea {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
  }
  .invoice-table {
    border: 1px solid #000 !important;
  }
  .invoice-table th,
  .invoice-table td {
    border: 1px solid #000 !important;
    color: #000 !important;
    background: transparent !important;
  }
  .el-dialog {
    position: static !important;
    width: 100% !important;
    margin: 0 !important;
  }
}
</style>
